import * as chokidar from 'chokidar'
import * as fs from 'fs'
import * as path from 'path'
import { URL } from 'url'
import * as download from "download"
import ErrorType from './errors';
export enum WatchType {
    Add = 'add',
    Change = 'change',
    Delete = 'unlink',
    Unlink = 'unlink',
    AddDir = 'addDir',
    Raw = 'raw'
}
export function watch(Path: string[], Type: WatchType[], Callback: Function) {
    let wathcer = chokidar.watch(Path)
    Type.forEach((d: string) => {
        wathcer.on(d, Callback)
    })
    return wathcer;
}
// export function 
/**
 * 文件下载库，自动判断是否为远程文件，
 * @param path 
 */
export async function read_file(path: string) {
    if (fs.existsSync(path)) {
        return fs.readFileSync(path)
    } else {
        let url = new URL(path);
        if ('http' == url.protocol.substr(0, 4)) {
            return await download(path)
        } else {
            throw new Error(ErrorType.READ_FILE_PATH_ERROR)
        }
    }
}

export function mkdirs(dirpath, mode = 0o777, callback = null) {
    if (fs.existsSync(dirpath)) {
        return true;
    } else {
        let parent_path = path.dirname(dirpath);
        if (fs.existsSync(parent_path)) {
            return fs.mkdirSync(dirpath, mode)
        } else {
            mkdirs(parent_path, mode)
            fs.mkdirSync(dirpath, mode)
        }
    }
}
export class filesystem {
    static async exist(file: string) {
        return new Promise((s, j) => {
            fs.exists(file, (rs) => {
                s(rs)
            })
        })
    }
    static async stat(file: string) {
        return new Promise((s, j) => {
            fs.stat(file, (err, stat) => {
                if (err) j(err);
                else s(stat)
            })
        })
    }
}